package com.kdgame.ggtest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.caveman.gamesdk.CavemanGameSdk;
import com.caveman.gamesdk.adapter.AbsRewardedVideoListener;
import com.caveman.gamesdk.open.BindUserInfo;
import com.caveman.gamesdk.open.LoginUserInfo;
import com.caveman.gamesdk.open.ProductDetails;
import com.caveman.gamesdk.open.RoleInfo;
import com.caveman.gamesdk.open.SDKCode;
import com.caveman.gamesdk.open.SDKPayListener;
import com.caveman.gamesdk.open.SdkCallbackListener;
import com.caveman.gamesdk.open.SdkLoginListener;
import com.caveman.gamesdk.open.SdkPayInfo;
import com.caveman.gamesdk.open.TimeZoneItem;
import com.caveman.gamesdk.open.TimeZoneList;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MainActivity extends Activity {
    private Activity mActivity;
    private EditText edt_sku;
    private TextView txt_title;
    private ProductDetails currentProductDetails;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mActivity = this;
        edt_sku = findViewById(R.id.edt_sku);
        txt_title = findViewById(R.id.txt_title);
        txt_title.setText("LiMeGameSDK  VersionCode:" + getVersionCode(mActivity) + " SDK Version:" + CavemanGameSdk.getInstance().cavemanGetSdkVersion());

        CavemanGameSdk.getInstance().cavemanOpenLog(true);
    }


    public String getVersionCode(Context context) {
        String packageName = "";
        try {
            String pkName = context.getApplicationContext().getPackageName();
            packageName = context.getApplicationContext().getPackageManager().getPackageInfo(pkName, 0).versionCode + "";

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return packageName;
    }

    @Override
    protected void onResume() {
        super.onResume();
        CavemanGameSdk.getInstance().onResume(mActivity);
    }

    @Override
    protected void onPause() {
        super.onPause();
        CavemanGameSdk.getInstance().onPause(mActivity);
    }

    @Override
    protected void onStop() {
        super.onStop();
        CavemanGameSdk.getInstance().onStop(mActivity);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        CavemanGameSdk.getInstance().onActivityResult(mActivity, requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void chinese(View view) {
        CavemanGameSdk.getInstance().cavemanSwitchLanguage(Locale.CHINA);
    }

    public void english(View view) {
        CavemanGameSdk.getInstance().cavemanSwitchLanguage(Locale.ENGLISH);
    }

    public void twLanguage(View view) {
        CavemanGameSdk.getInstance().cavemanSwitchLanguage(Locale.TRADITIONAL_CHINESE);
    }

    public void sdkUserTestServer(View view) {
        CavemanGameSdk.getInstance().cavemanUseTestServer();
        Log.e("MainActivity", CavemanGameSdk.getInstance().cavemanGetPrivacyPolicyUrl());
    }

    public void sdkInit(View view) {
        CavemanGameSdk.getInstance().cavemanSdkInit(mActivity, new SdkCallbackListener<String>() {
            @Override
            public void callback(int code, String response) {
                switch (code) {
                    case SDKCode.SUCCESS:
                        Toast.makeText(mActivity, "初始化成功", Toast.LENGTH_SHORT).show();
                        break;
                    case SDKCode.FAILURE:
                        Toast.makeText(mActivity, response, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });

        CavemanGameSdk.getInstance().cavemanSetQuestionListener(new SdkCallbackListener<String>() {
            @Override
            public void callback(int code, String urlString) {
                if (code == SDKCode.QUESTION_SHOW) {
                    Log.e("11111111", "问卷调查回调：" + urlString);
                    Intent intent = new Intent();
                    intent.setData(Uri.parse(urlString));//Url 就是你要打开的网址
                    intent.setAction(Intent.ACTION_VIEW);
                    startActivity(intent); //启动浏览器
                } else {
                    Toast.makeText(mActivity, "无需参加调查问卷", Toast.LENGTH_SHORT).show();
                }
            }
        });

        CavemanGameSdk.getInstance().cavemanSetSdkLoginListener(new SdkLoginListener() {
            @Override
            public void onLogin(int code, LoginUserInfo user) {
                if (code == SDKCode.SUCCESS) {
                    Toast.makeText(mActivity, "登录成功-->" + user.getUserID(), Toast.LENGTH_SHORT).show();

                    CavemanGameSdk.getInstance().cavemanGetBindUserInfo(mActivity, new SdkCallbackListener<BindUserInfo>() {
                        @Override
                        public void callback(int code, BindUserInfo response) {
                            Log.e("cavemanGetBindUserInfo", response.toString());
                        }
                    });
                } else if (code == SDKCode.FAILURE) {
                    Toast.makeText(mActivity, "登录失败：失败原因-->" + user.getErrorMsg(), Toast
                            .LENGTH_SHORT).show();
                } else if (code == SDKCode.CANCLE) {
                    Toast.makeText(mActivity, "登录取消", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onLogout(int code, String msg) {
                if (code == SDKCode.SUCCESS) {
                    Log.e("11111", "注销成功");
                } else if (code == SDKCode.FAILURE) {
                    Log.e("11111", "注销失败" + msg);
                }
            }
        });


        CavemanGameSdk.getInstance().cavemanSetAccountBindListener(new SdkCallbackListener<String>() {
            @Override
            public void callback(int code, String response) {
                if (code == SDKCode.BIND_FAILURE) {
                    Toast.makeText(mActivity, "绑定失败", Toast.LENGTH_SHORT).show();
                } else if (code == SDKCode.BIND_GOOGLE_SUCCESS) {
                    Toast.makeText(mActivity, "google绑定成功", Toast.LENGTH_SHORT).show();
                } else if (code == SDKCode.BIND_FACEBOOK_SUCCESS) {
                    Toast.makeText(mActivity, "facebook绑定成功", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void sdkGoogleLogin(View view) {
        CavemanGameSdk.getInstance().cavemanSdkSilentLogin(this);
    }

    public void sdkLogin(View view) {
        CavemanGameSdk.getInstance().cavemanSdkLogin(this);
    }


    public void sdkLoginOut(View view) {
        CavemanGameSdk.getInstance().cavemanSdkLoginOut();
    }

    public void sdkUserAuth(View view) {
        CavemanGameSdk.getInstance().cavemanOnNewPlayer();
    }

    public void sdkSwitchUser(View view) {
        CavemanGameSdk.getInstance().cavemanSdkSwitchLogin(this);
    }

    /**
     * 获取大区列表
     *
     * @param view
     */
    private TimeZoneList timeZoneList;

    public void sdkGetZoneList(View view) {
        //获取大区列表
        CavemanGameSdk.getInstance().cavemanGetZoneList(mActivity, true, new SdkCallbackListener<TimeZoneList>() {
            @Override
            public void callback(int code, TimeZoneList response) {
                if (code == SDKCode.SUCCESS) {
                    timeZoneList = response;
                    Toast.makeText(mActivity, "获取成功", Toast.LENGTH_SHORT).show();

                    Log.e("MainActivity", "getDefaultZone--->" + response.getDefaultZone());
                    for (TimeZoneItem timeZoneItem : response.getZoneList()) {
                        Log.e("MainActivity", "Zone list--->" + timeZoneItem.toString());
                    }
                } else {
                    Toast.makeText(mActivity, "获取失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 切换大区
     *
     * @param view
     */
    private int zoneIndex = 0;

    public void sdkSwitchZone(View view) {
        if (timeZoneList == null || timeZoneList.getZoneList().size() <= 0) {
            Toast.makeText(mActivity, "请先获取大区列表", Toast.LENGTH_SHORT).show();
            return;
        }
        ++zoneIndex;
        if (zoneIndex > timeZoneList.getZoneList().size() - 1) {
            zoneIndex = 0;
        }
        String zoneKey = timeZoneList.getZoneList().get(zoneIndex).getKey();
        Log.e("MainActivity", "current zone key--->" + zoneKey);
        CavemanGameSdk.getInstance().cavemanSwitchZone(mActivity, zoneKey, true, new SdkCallbackListener<String>() {
            @Override
            public void callback(int code, String response) {
                if (code == SDKCode.SUCCESS) {
                    Toast.makeText(mActivity, "切换成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mActivity, "切换失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    public void sdkCurrentZone(View view) {
        Toast.makeText(mActivity, CavemanGameSdk.getInstance().cavemanGetCurrentZoneKey(), Toast.LENGTH_SHORT).show();
    }

    public void sdkGetBindUser(View view) {
        CavemanGameSdk.getInstance().cavemanGetBindUserInfo(mActivity, new SdkCallbackListener<BindUserInfo>() {
            @Override
            public void callback(int code, BindUserInfo response) {
                if (code == SDKCode.SUCCESS) {
                    if (response.isGoogleBind()) {
                        Toast.makeText(mActivity, "google 已绑定", Toast.LENGTH_SHORT).show();
                    }

                    if (response.isFacebookBind()) {
                        Toast.makeText(mActivity, "facebook 已绑定", Toast.LENGTH_SHORT).show();
                    }
                    Toast.makeText(mActivity, response.toString(), Toast.LENGTH_SHORT).show();
                } else {
                    //获取用户信息失败，response是null
                }
            }
        });
    }

    public void sdkQueryProduct(View view) {
        ArrayList<String> listProduct = new ArrayList<>(5);
        listProduct.add("com.kdgame.gameplaylogin.0.99");
        listProduct.add("com.kdgame.gameplaylogin.4.99");
        listProduct.add("com.kdgame.gameplaylogin.9.99");
        listProduct.add("android.test.purchased");
        CavemanGameSdk.getInstance().cavemanQueryProduct(this, listProduct,
                new SdkCallbackListener<List<ProductDetails>>() {
                    @Override
                    public void callback(int code, List<ProductDetails> response) {
                        if (code == SDKCode.SUCCESS) {
                            currentProductDetails = response.get(0);

                            Log.e("MainActivity", "******************************");
                            for (ProductDetails productDetails : response) {
                                Log.e("Main", productDetails.toString());
                            }
                            Log.e("MainActivity", "******************************\n\n\n");
                        } else if (code == SDKCode.FAILURE) {
                            Toast.makeText(mActivity, "查询商品错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    public void sdkPay(View view) {
        if (currentProductDetails == null) {
            Toast.makeText(mActivity, "请先查询商品列表", Toast.LENGTH_SHORT).show();
            return;
        }

        SdkPayInfo payInfo = new SdkPayInfo();
        payInfo.setCpOrderSn(System.currentTimeMillis() + "");
        payInfo.setGameServer("101");

        payInfo.setGoodsName("钻石333");
        payInfo.setSkuId(edt_sku.getText().toString());
        payInfo.setRoleName("roleName111");
        payInfo.setRoleId("123");
        payInfo.setExt("扩展信息");
        payInfo.setCurrencyType(currentProductDetails.getCurrencyCode());
        payInfo.setCurrencyAmount(currentProductDetails.getLocalePrice());

        CavemanGameSdk.getInstance().cavemanSdkPay(this, payInfo, new SDKPayListener() {
            @Override
            public void onPayFinish() {
                Toast.makeText(mActivity, "支付完成", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPayFailed(String msg) {
                Toast.makeText(mActivity, "支付失败-->" + msg, Toast.LENGTH_SHORT).show();
            }
        });
    }


    public void sdkUserCenter(View view) {
        CavemanGameSdk.getInstance().cavemanOpenUserCenter(mActivity);
    }

    public void sdkFeedback(View view) {
        CavemanGameSdk.getInstance().cavemanOpenFeedBack(mActivity);
    }

    public void sdkBindGoogle(View view) {
        CavemanGameSdk.getInstance().cavemanBindGoogle(mActivity);
    }

    public void sdkBindFacebook(View view) {
        CavemanGameSdk.getInstance().cavemanBindFacebook(mActivity);
    }

    public void sdkExit(View view) {
        CavemanGameSdk.getInstance().cavemanExitGame(mActivity, new SdkCallbackListener<String>() {
            @Override
            public void callback(int code, String response) {
                if (code == SDKCode.EXIT_GAME) {
                    Toast.makeText(mActivity, "EXIT_GAME", Toast.LENGTH_SHORT).show();

                    System.exit(0);
                } else if (code == SDKCode.EXIT_CANCLE) {
                    Toast.makeText(mActivity, "EXIT_CANCLE", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 上报类型
     */
    private int type = 0;

    public void reportRoleData(View view) {
        ++type;
        if (type > 4) {
            type = 1;
        }

        RoleInfo roleInfo = new RoleInfo();
        roleInfo.setServerID("111111")
                .setServerName("server_name_B")
                .setRoleId("222222")
                .setRoleName("role_name_D")
                .setUnion("union_E")
                .setRoleLevel(type)
                .setPower("" + type)
                .setServerStartTime(System.currentTimeMillis())
                .setReportType(type);

        CavemanGameSdk.getInstance().cavemanReportRoleData(this, roleInfo);
    }

    public void reportStartGame(View view) {

        RoleInfo roleInfo = new RoleInfo();
        roleInfo.setServerID("111111")
                .setServerName("server_name_B")
                .setRoleId("222222")
                .setRoleName("role_name_D")
                .setUnion("union_E")
                .setRoleLevel(type)
                .setPower("" + type)
                .setServerStartTime(System.currentTimeMillis())
                .setReportType(5);

        CavemanGameSdk.getInstance().cavemanReportRoleData(this, roleInfo);
    }

    public void openDiscord(View view) {
        CavemanGameSdk.getInstance().cavemanDiscordOpenPage(mActivity);
    }

    public void openFacebook(View view) {
        CavemanGameSdk.getInstance().cavemanFacebookOpenPage(mActivity);
    }

    public void openFacebookDownload(View view) {
        CavemanGameSdk.getInstance().cavemanFacebookShareGame(this, new SdkCallbackListener<String>() {
            @Override
            public void callback(int code, String response) {
                Toast.makeText(mActivity, "Share Url: " + response, Toast.LENGTH_SHORT).show();
                switch (code) {
                    case SDKCode.SUCCESS:
                        //分享成功
                        break;
                    case SDKCode.CANCLE:
                        //用户取消
                        break;
                    case SDKCode.FAILURE:
                        //分享失败
                        break;
                }
            }
        });
    }

    public void fabookSharePhoto(View view) {
        //String filePath = Environment.getExternalStorageDirectory() + "/image.jpg";
        //Bitmap image = BitmapFactory.decodeFile(filePath);

        AssetManager assetManager = this.getAssets();
        try {
            InputStream inputStream = assetManager.open("share_image.jpg");//filename是assets目录下的图片名
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            CavemanGameSdk.getInstance().cavemanFacebookShareImage(this, bitmap, new SdkCallbackListener<String>() {
                @Override
                public void callback(int code, String response) {
                    Toast.makeText(mActivity, "Share Image: " + response, Toast.LENGTH_SHORT).show();
                    switch (code) {
                        case SDKCode.SUCCESS:
                            //分享成功
                            break;
                        case SDKCode.CANCLE:
                            //用户取消
                            break;
                        case SDKCode.FAILURE:
                            //分享失败
                            break;
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void enableIronSource(View view) {
        //启用广告接口
        CavemanGameSdk.getInstance().cavemanAdEnable(this);

        //测试广告对接是否完成 ******正式上线移除掉******
        CavemanGameSdk.getInstance().cavemanAdValidateIntegration(this);
        //广告状态监听
        CavemanGameSdk.getInstance().cavemanAdSetRewardedVideoListener(new AbsRewardedVideoListener() {
            @Override
            public void onRewardedVideoAdOpened() {
                super.onRewardedVideoAdOpened();
            }

            @Override
            public void onRewardedVideoAdClosed() {
                super.onRewardedVideoAdClosed();
            }

            @Override
            public void onRewardedVideoAvailabilityChanged(boolean b) {
                super.onRewardedVideoAvailabilityChanged(b);
                if (b) {
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mActivity, "广告可以播放了", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onRewardedVideoAdStarted() {
                super.onRewardedVideoAdStarted();
            }

            @Override
            public void onRewardedVideoAdEnded() {
                super.onRewardedVideoAdEnded();
            }

            @Override
            public void onRewardedVideoAdRewarded(final com.ironsource.mediationsdk.model.Placement placement) {
                super.onRewardedVideoAdRewarded(placement);
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mActivity, placement.getPlacementName() + " 播放完毕，获得奖励", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onRewardedVideoAdShowFailed(com.ironsource.mediationsdk.logger.IronSourceError ironSourceError) {
                super.onRewardedVideoAdShowFailed(ironSourceError);
            }

            @Override
            public void onRewardedVideoAdClicked(com.ironsource.mediationsdk.model.Placement placement) {
                super.onRewardedVideoAdClicked(placement);
            }
        });
    }

    public void showRewardedVideo(View view) {
        //播放默认视频
        CavemanGameSdk.getInstance().cavemanAdShowRewardedVideo();
        //播放指定视频
        //CavemanGameSdk.getInstance().adShowRewardedVideo(placementName);
    }
}